<template>
	<view class="apply-pages pt-md" :style="{background:pageColor}" v-if="isLoad">
		<view class="apply-form pl-lg pr-lg">
			<view class="fill-base radius-16 rel">
				<view class="flex-between ml-lg mr-lg b-1px-b">
					<view class="item-text">联系人</view>
					<input v-model="form.user_name" type="text" class="item-input flex-1" maxlength="20"
						:placeholder="rule[0].errorMsg" placeholder-class="c-caption" />
				</view>
				<view class="flex-between ml-lg mr-lg">
					<view class="item-text">手机号</view>
					<view class="flex-1">
						<view class="flex-between">
							<input :disabled="!is_send" v-model="form.mobile" type="text" class="item-input flex-1"
								maxlength="11" :placeholder="rule[1].errorMsg" placeholder-class="c-caption" />
							<view>
								<view @tap.stop="toResetPhone" class="f-caption" :style="{color:primaryColor}"
									v-if="!is_send">更换手机号</view>
							</view>
						</view>
						<view class="flex-between pb-md" v-if="configInfo.short_code_status && is_send">
							<input v-model="form.phone_code" type="text" maxlength="6"
								style="font-size: 26rpx;color: #A9A9A9;" placeholder-class="c-caption"
								placeholder="请输入验证码" />
							<view @tap.stop="toSend" class="f-caption text-right" style="width:180rpx"
								:style="{color:primaryColor}">
								{{authTime>0?`重新获取(${authTime}s)`:'获取验证码'}}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between ml-lg mr-lg b-1px-b">
					<view class="item-text">服务地址</view>
					<view @tap.stop="toChooseLocation" class="item-input text flex-1">
						<view class="flex-between">
							<view :class="[{'c-caption':!form.address}]">{{form.address || rule[2].errorMsg}}</view>
							<i class="iconfont iconjuli" :style="{color: primaryColor}"></i>
						</view>
					</view>
				</view>
				<view class="flex-between ml-lg mr-lg">
					<view class="item-text">门牌号</view>
					<input v-model="form.address_info" type="text" class="item-input flex-1"
						:placeholder="rule[3].errorMsg" placeholder-class="c-caption" />
				</view>
			</view>
			<view class="fill-base mt-md radius-16">
				<view class="flex-between ml-lg mr-lg">
					<view class="item-text flex-1" style="width: 300rpx;">设为默认地址</view>
					<!-- status 1默认； -->
					<view @tap.stop="form.status = form.status ==1 ? 0 : 1" class="item-input">
						<i class="iconfont icon-switch" :class="[{'icon-switch-on':form.status==1}]"
							:style="{color:form.status==1? primaryColor:'#f2f2f2'}"></i>
					</view>
				</view>
			</view>
			<view class="f-icontext c-caption mt-md"> 设置后，下单时优先展示该地址</view>
		</view>

		<view class="space-max-footer"></view>

		<fix-bottom-button @cancel="toDel" @confirm="submit" :text="textArr" bgColor="#fff"></fix-bottom-button>


		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<longbingbing-app-check-auth type="location" ref="app_check_item"
			@confirm="toConfirmChooseLoca"></longbingbing-app-check-auth>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				options: {},
				authTime: 0,
				timer: null,
				is_send: true,
				textArr: [{
					text: '删除',
					type: 'cancel'
				}, {
					text: '保存',
					type: 'confirm'
				}],
				form: {
					id: 0,
					user_name: '',
					mobile: '',
					address: '',
					address_info: '',
					province: '',
					city: '',
					area: '',
					lng: '',
					lat: '',
					status: 0,
					phone_code: ''
				},
				rule: [{
						name: "user_name",
						checkType: "isNotNull",
						errorMsg: "请输入联系人姓名",
						regType: 2
					}, {
						name: "mobile",
						checkType: "isMobile",
						errorMsg: "请输入手机号"
					},
					{
						name: "address",
						checkType: "isNotNull",
						errorMsg: "请选择您的地址"
					},
					{
						name: "address_info",
						checkType: "isNotNull",
						errorMsg: "请输入某酒店/XX房间(某小区/XX号)",
						regType: 2
					},
				],
				lockTap: false
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			mineInfo: state => state.user.mineInfo,
		}),
		async onLoad(options) {
			this.options = options
			await this.initIndex()
			// #ifdef H5
			this.$jweixin.hideOptionMenu()
			// #endif
		},
		watch: {
			'form.mobile'(newval) {
				let {
					phone = ''
				} = this.mineInfo
				if (newval && newval == phone) {
					this.is_send = false
					if (this.timer) clearInterval(this.timer)
				}
			}
		},
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo', 'getMineInfo']),
			...mapMutations(['updateUserItem', 'updateOrderItem']),
			async initIndex() {
				let {
					id = 0
				} = this.options
				uni.setNavigationBarTitle({
					title: id ? `编辑地址` : `添加新地址`
				})
				await this.getMineInfo()
				let {
					phone = ''
				} = this.mineInfo
				if (phone) {
					this.form.mobile = phone
					this.is_send = false
				}
				if (!id) {
					this.textArr.splice(0, 1)
					this.isLoad = true
					this.$util.setNavigationBarColor({
						bg: this.primaryColor
					})
					return
				}
				let data = await this.$api.mine.addressInfo({
					id
				})
				for (let key in this.form) {
					this.form[key] = data[key]
				}
				this.is_send = this.form.mobile ? false : true
				this.$util.setNavigationBarColor({
					bg: this.primaryColor
				})
				this.isLoad = true
			},
			initRefresh() {
				this.initIndex()
			},
			// 选择地区
			async toChooseLocation() {
				// #ifdef APP-PLUS
				this.$util.goUrl({
					url: `/user/pages/choose/addr?from=useraddr`
				})
				// if (plus.os.name == 'Android' && plus.navigator.checkPermission(
				// 		'android.permission.ACCESS_FINE_LOCATION') ===
				// 	'undetermined') {
				// 	this.$refs.app_check_item.open()
				// } else {
				// 	this.toConfirmChooseLoca()
				// }
				// #endif
				// #ifndef APP-PLUS
				this.toConfirmChooseLoca()
				// #endif
			},
			async toConfirmChooseLoca() {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				let {
					lat,
					lng,
					name,
					address
				} = await this.$util.chooseLocation()
				if (!lat && !lng) return
				if (name && !address) {
					this.$util.showToast({
						title: `请选择具体的地址`
					})
					return
				}
				let {
					province,
					city,
					area
				} = await this.$util.getCityAddr(address)

				let form = Object.assign({}, this.form, {
					lat,
					lng,
					address,
					address_info: name,
					province,
					city,
					area
				})
				this.form = form
			},
			toResetPhone() {
				this.form.mobile = ''
				this.is_send = true
			},
			// 发送验证码
			async toSend() {
				let {
					authTime
				} = this
				if (authTime) return
				let {
					mobile: phone = ''
				} = this.form
				if (!phone || !/^(1[0-9]{10})$/.test(phone)) {
					this.$util.showToast({
						title: !phone ? `请输入手机号` : `${phone} 手机号无效`
					});
					return;
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					await this.$api.user.sendShortMsg({
						phone
					})
					this.$util.hideAll()
					this.lockTap = false
					this.form.phone_code = ''
					let time = 60
					this.timer = setInterval(() => {
						if (time === 0) {
							clearInterval(this.timer)
							return
						}
						time--
						this.authTime = time
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			async toDel() {
				let [res_del, {
					confirm
				}] = await uni.showModal({
					title: '提示',
					content: "请确认是否要删除此数据?"
				})
				if (!confirm) return;
				let {
					id
				} = this.form
				let check_id = 0
				try {
					let {
						check_id: checkid
					} = this.$util.getPage(-1)
					check_id = checkid
				} catch (e) {
					// #ifdef H5
					history.back()
					// #endif
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					await this.$api.mine.addressDel({
						id
					})
					this.$util.hideAll()
					this.$util.showToast({
						title: `删除成功`,
					});
					if (id == check_id) {
						this.updateOrderItem({
							key: 'haveOperItem',
							val: true
						})
					}
					setTimeout(() => {
						this.lockTap = false
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			//表单验证
			validate(param) {
				let validate = new this.$util.Validate();
				this.rule.map(item => {
					let {
						name,
					} = item
					validate.add(param[name], item);
				})
				let message = validate.start();
				return message;
			},
			async submit() {
				let param = this.$util.deepCopy(this.form)
				let msg = this.validate(param);
				if (msg) {
					this.$util.showToast({
						title: msg
					});
					return;
				}
				let {
					short_code_status
				} = this.configInfo
				let {
					is_send
				} = this
				if (short_code_status && is_send && (!param.phone_code || param.phone_code.length != 6)) {
					this.$util.showToast({
						title: `请输入6位数短信验证码`
					})
					return
				}
				if (!short_code_status || !is_send) {
					delete param.phone_code
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()

				try {
					let methodModel = param.id ? `addressUpdate` : `addressAdd`
					if (!param.province) {
						let {
							province,
							city,
							area
						} = await this.$util.getCityAddr(param.address)
						param = Object.assign({}, param, {
							province,
							city,
							area
						})
					}
					await this.$api.mine[methodModel](param)
					this.$util.hideAll()
					this.$util.showToast({
						title: `保存成功`,
					})
					if (this.timer) {
						clearInterval(this.timer)
					}
					setTimeout(() => {
						this.$util.back()
						this.$util.goUrl({
							url: 1,
							openType: `navigateBack`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			}
		}
	}
</script>


<style lang="scss">
	// .mobile-box{
	// 	z-index: 9;
	// 	top: 180rpx;
	// 	left: 230rpx;
	// 	box-shadow: 1px 0px 10px #ccc;
	// 	.mobile-box-icon{
	// 		width: 0px;
	// 		height: 0px;
	// 		border: 10px solid #fff;
	// 		border-top-color: transparent;
	// 		border-left-color: transparent;
	// 		border-right-color: transparent;
	// 		left: 50%;
	// 		margin-left: -10px;
	// 		top: -15px;
	// 	}
	// }
</style>